package com.itheima.sc.filter;

import cn.hutool.core.util.StrUtil;
import com.itheima.sc.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.rmi.RemoteException;

//@Component
//@WebFilter(urlPatterns = "/*",filterName = "MyGlobalFilter")
//@Slf4j
public class MyTestFilter implements Filter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //进行格式的转换
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取当前路径
        String uri = request.getRequestURI();
        //判断路径接口
        if (StrUtil.equals(uri,"/admin/login")){
            //放行
            filterChain.doFilter(request,response);
            return;
        }
        //1.获取token
//      String authorization = request.getHeaders().getFirst("Authorization");
       String  authorization= request.getHeader("Authorization");
        String token = authorization.replace("Bearer ", "");
        //进行token的校验  并根据token获取用户id
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int i = AppJwtUtil.verifyToken(claimsBody);
        //-1：有效，0：有效，1：过期，2：过期
        if (i == -1 || i == 0) {
            String adminId = claimsBody.get("id").toString();
            //将获取的adminId 即用户id存入redis中
            String redisKey = "CHECK_ADMINID";
            stringRedisTemplate.opsForValue().set(redisKey,adminId);
            //放行
            filterChain.doFilter(request,response);
            return;
        }
       throw new RemoteException("token已经过期");
    }
}